<template>
  <a-row class="card-nopd-out-container department-container">
    <a-col :span="3" class="tree-box pt-20">
      <side-tree v-if="treeData.length" :defaultSelect="selectedKeys" @onSelect="onTreeSelect" @onEdit="onTreeEdit" @onDelete="onTreeDelete" :treeData="treeData" />
      <div class="px-20 border-top">
        <div v-if="isEnvLocal" class="mt-20">
          <a-button block type="primary" @click="syncData(syncDataAry)"> {{$t('common.sync')}}</a-button>
        </div>
        <div v-else>
          <a-upload name="file" :action="url.uplaodUrl" :headers="uploadHeaders" @change="handleImportExcel" :show-upload-list="false" :before-upload="beforeUpload">
            <div style="width: 179px">
              <a-button class="mt-20 mb-15" block type="primary">
                <template #icon>
                  <UserAddOutlined />
                </template> {{$t('common.staffImport')}}
              </a-button>
            </div>
          </a-upload>
          <a-row :gutter="10">
            <a-col :span="24">
              <a-button block @click="()=> handleExportXls(url.exportUrl, $t('menu.basic:staff') )">
                {{ $t('other.exportEmployee') }}
              </a-button>
            </a-col>
            <a-col :span="24" class="mt-15">
              <a-button @click="()=> handleExportXls(url.templateUrl, $t('sysManage.emplTemplate'))" block>
                <!-- <template #icon>
                  <DownloadOutlined />
                </template> -->
                {{ $t('common.downMode') }}
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-col>
    <a-col :span="21" class="table-box pt-20 pr-20">
      <a-row>
        <a-col :span="isEnvLocal ? 12: 24" :class="['blue-line', {'mb-20': !isEnvLocal}]">
          {{selectedDpdName}}
        </a-col>
        <a-col :span="12" v-if="!isEnvLocal">
          <a-space>
            <a-button type="primary" @click="onTableEdit({}, true)">{{$t('common.addNew')}}</a-button>
            <a-button ghost type="warning" @click="handleDelete(null)" :disabled="!selectedRowKeys.length">{{$t('common.del')}}</a-button>
          </a-space>
        </a-col>
        <a-col :span="12" class="text-right">
          <a-input-search v-model:value.trim="queryParam.staffNo" enter-button :placeholder="$t('basicData.jobNoName')" @search="loadData" style="width: 215px" />
        </a-col>
      </a-row>
      <a-table rowKey="id" :loading="loading" class="mt-15" bordered size="small" :dataSource="dataSource" :columns="columns" @change="handleTableChange" :pagination="ipagination" :scroll="{x: 800, y: isEnvLocal ? 'calc(100vh - 338px)' : 'calc(100vh - 390px)'}" :rowSelection="isEnvLocal ?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, fixed: 'left'}">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operate'">
            <span class="table-operate-container">
              <a-button type="link" class="primary-link" @click="onTableEdit(record)">{{$t('common.editor')}}</a-button>
              <a-divider type="vertical" />
              <a-button type="link" class="warning-link" @click="handleDelete(record.id, true)">{{$t('common.del')}}</a-button>
              <a-divider type="vertical" />
              <a-button type="link" class="primary-link" @click="onGoodProc(record)">{{$t('basicData.goodProcess')}}</a-button>
            </span>
          </template>
        </template>
      </a-table>
    </a-col>
    <commone-modal ref="modalForm" tableName="employeesGroup" :cloSapn="24" :modalTitle="$t('sysManage.group')" @ok="otherOperate">
    </commone-modal>
    <operateEmpModal ref="operateEmpModalRef" @ok="loadData" />
    <CustomModal ref="customModalRef" @ok="onTreeConformDel" />
    <SyncDataModal  ref="syncDataModalRef" />
    <GoodAtProcModal  ref="goodAtProcModalRef" @ok="loadData" />
  </a-row>
</template>

<script>
import { filterObj, getBaseUrl } from '@/utils'
import { cloneDeep } from 'lodash'
import axios from '@/utils/request'
import SideTree from './modules/sideTree.vue'
import { ListMixinPm } from '@/mixin/listMixinPm.js'
// import { DownloadOutlined, UserAddOutlined } from '@ant-design/icons-vue'
import { UserAddOutlined } from '@ant-design/icons-vue'
import CommoneModal from '@/components/commonModal/normalModal.vue'
import operateEmpModal from './modules/operateEmpModal.vue'
import { normalColumns, localColumns, originTreeList } from './modules/employeesConfig'
import CustomModal from '@/components/confirmModal/customModal.vue'
import SyncDataModal from '@/components/syncModal/syncDataModal.vue'
import GoodAtProcModal from './modules/goodAtProcModal.vue'
import { store } from '@/store'
export default {
  name: 'sysEmployees',
  components: {
    SideTree,
    // DownloadOutlined,
    UserAddOutlined,
    CommoneModal,
    operateEmpModal,
    CustomModal,
    SyncDataModal,
    GoodAtProcModal
  },
  mixins: [ListMixinPm],
  data () {
    return {
      selectedKeys: ['all'],
      columns: [],
      url: {
        list: '/api/basic/staff/page',
        treeList: '/api/basic/staff-group/list',
        delete: '/api/basic/staff/delete',
        deleteTree: '/api/basic/staff-group/delete',
        templateUrl: '/api/basic/staff/export-template',
        exportUrl: '/api/basic/staff/export-data',
        uplaodUrl: `${getBaseUrl(process.env.NODE_ENV)}/api/basic/staff/import-data`,
        sync: '/api/system/iot/sync-cloud-data'
      },
      originTreeList,
      treeData: [],
      selectedDpdName: this.$t('common.all'),
      operateType: 'add',
      deleteGroupInfo: {},
      selectTreeInfo: {},
      storeName: 'getEmpl',
      syncDataAry: [
        { syncIotCloudDataType: 'ihs:basic:staffGroup' },
        { syncIotCloudDataType: 'ihs:basic:staff' },
        { syncIotCloudDataType: "ihs:basic:profession" },
        { syncIotCloudDataType: "ihs:basic:skillGrade" }
      ]
    }
  },
  methods: {
    getQueryParams () {
      if (!this.selectedKeys.length) {
        return false
      } else {
        let { id, flag } = this.selectTreeInfo
        let param = cloneDeep(this.queryParam)
        if (param.staffNo) param.nickName = param.staffNo
        param.groupId = ['all', 'notGrouped'].includes(id) ? null : id
        param.flag = flag
        param.sortingFields = this.isorter.field ? [this.isorter] : null
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      }
    },
    onTreeSelect (selectedKeys, selectedNodes) {
      if (selectedKeys.length) {
        this.selectTreeInfo = selectedNodes[0]
        this.selectedDpdName = selectedNodes[0].name
        this.selectedKeys = selectedKeys
        this.loadData(1)
      }
    },
    initPage () {
      this.selectedDpdName = this.$t('common.all')
      this.selectedKeys = ['all']
      this.selectTreeInfo = { name: this.$t('common.all'), id: 'all', isParent: true }
      this.ipagination.current = 1
      this.ipagination.pageSize = 10
    },
    onTreeEdit (info, isAdd) {
      this.operateType = isAdd ? 'add' : 'edit'
      this.handleEdit(isAdd ? {} : info, !isAdd)
    },
    onTreeDelete (record) {
      //  组别删除
      this.deleteGroupInfo = record
      let content = `${this.$t('sysManage.confirmDel')}「${record.name}」${this.$t('sysManage.what')}？<br/>${this.$t('sysManage.emplDelTip')}。`
      this.$refs.customModalRef.open({ content })
    },
    async onTreeConformDel () {
      try {
        const res = await axios.deleteAction(this.url.deleteTree, [this.deleteGroupInfo.id])
        if (res.success) {
          this.$message.success(res.msg)
          this.searchReset()
        } else {
          this.$message.warning(res.msg)
        }
      } catch {
        this.$message.warning(this.$t('common.errorTip'))
      }
    },
    onGoodProc(record) {
      this.$refs.goodAtProcModalRef.open(record)
    },
    onTableEdit (record, isEdit) {
      this.operateType = 'table'
      this.$refs.operateEmpModalRef.edit(record, isEdit)
    },
    async otherOperate (params) {
      if (this.operateType == 'delete') {
        this.initPage()
      } else if (this.operateType == 'edit') {
        if (params.id == this.selectedKeys[0]) this.selectedDpdName = params.name
      }
      await this.getTreeData()
      this.loadData()
    },
    async getTreeData () {
      try {
        const res = await axios.postAction(this.url.treeList, {})
        if (res.success && res.data && res.data.length) {
          let list = cloneDeep(this.originTreeList)
          list[0].children = [
            ...res.data,
            { name: this.$t('sysManage.onGroup'), id: 'notGrouped', flag: true }
          ]
          this.treeData = list
        } else {
          this.treeData = cloneDeep(this.originTreeList)
        }
      } catch {
        this.treeData = cloneDeep(this.originTreeList)
      }
      await store.dispatch('getEmplGruop')
    },
    async searchReset () {
      this.initPage()
      await this.getTreeData()
      this.loadData()
    },
    async handleImportExcel (info) {
      if (info.file.status !== 'uploading') {
        console.log('uploading')
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.searchReset()
        } else {
          this.$message.error(info.file.response.msg)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${this.$t('common.fileUploadErr')}: ${info.file.msg} `)
      }
    },
  },
  async created () {
    this.columns = this.isEnvLocal ? localColumns : normalColumns
    await this.getTreeData()
  }
}
</script>